package com.example.chapter08;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;

import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter08.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpinnerIconActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private static final int[] iconArray = {
            R.drawable.earth, R.drawable.mars, R.drawable.jupiter, R.drawable.saturn,
            R.drawable.neptune, R.drawable.venus
    };
    private final static String[] starArray = {"Earth", "Mars", "Jupiter", "Saturn", "Neptune", "Venus"};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_icon);
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < iconArray.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("icon", iconArray[i]);
            map.put("name", starArray[i]);
            list.add(map);
        }

        // 创建SimpleAdapter适配器，将图标和文本绑定到item_simple.xml布局文件
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, R.layout.item_simple,
                new String[]{"icon", "name"},
                new int[]{R.id.iv_icon, R.id.tv_name});

        Spinner sp_icon = findViewById(R.id.spinner_icon);
        sp_icon.setAdapter(simpleAdapter);
        sp_icon.setSelection(0); // 设置默认选中第一项
        sp_icon.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        ToastUtil.show(this, "您选择的是" + starArray[position]);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}